package netty

import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.bootstrap.Bootstrap
import io.netty.channel.*
import io.netty.channel.nio.NioEventLoopGroup


class NettyClient(private var host: String, private var port: Int) {

    private var channel: Channel? = null

    @Throws(Exception::class)
    fun start() {
        val group = NioEventLoopGroup()

        val b = Bootstrap()
        b.group(group).channel(NioSocketChannel::class.java)  // 使用NioSocketChannel来作为连接用的channel类
            .handler(ClientHandler())
        //发起异步连接请求，绑定连接端口和host信息
        val future = b.connect(host, port).sync()

        future.addListener(ChannelFutureListener {
            if (future.isSuccess) {
                println("连接服务器成功")

            } else {
                println("连接服务器失败")
                future.cause().printStackTrace()
                group.shutdownGracefully() //关闭线程组
            }
        })

        this.channel = future.channel()
    }

    fun getChannel(): Channel? {
        return channel
    }

}
